package com.mtf.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author matengfei
 * @Date 2024/7/1 18:23
 * @PackageName:com.mtf.config
 * @ClassName: JedisConfig
 * @Description: Jedis连接池
 * @Version 1.0
 */
@Configuration
public class JedisConfig {
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10); // 设置连接池的最大连接数
        poolConfig.setMaxIdle(5);   // 设置连接池的最大空闲连接数
        poolConfig.setMinIdle(1);   // 设置连接池的最小空闲连接数

        JedisConnectionFactory factory = new JedisConnectionFactory(poolConfig);
        factory.setHostName("127.0.0.1");
        factory.setPort(6379);
        factory.setUsePool(true);
        return factory;
    }

    @Bean("jedisTemplate")
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        //template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(objectMapper);
        return template;
    }
}
